import json
from tabnanny import check
from urllib.parse import ParseResult
from xml.dom.minidom import ProcessingInstruction

# 导入Django核心模块中的序列化器，用于将Django模型转换为其他格式，如JSON、XML等
from django.core import serializers

# 导入Django序列化功能，以便在需要时将模型序列化
from django.core.serializers import serialize
from django.db.models import Q

# 导入HttpResponse和JsonResponse类，用于构建HTTP响应和JSON响应
from django.http import HttpResponse, JsonResponse

# 导入render函数，它用于根据请求和模板渲染网页
from django.shortcuts import render

from django.views import View
# 导入分页类
from django.core.paginator import Paginator
from backend.models import TSetmeal, UploadFileForm, TCheckgroupCheckitem, TSetmealCheckgroup
import pymysql
import  random
import redis
from backend.qiliuyun import handle_uploaded_file, handle_delet_file


class Stmeal(View):
    def get(self,request, Page, pageSize):

        queryString = request.GET.get("queryString")
        if(queryString==None):
            setMeal_list=TSetmeal.objects.filter(is_show=1)
            paginator = Paginator(setMeal_list, pageSize)

            # 获取指定页码的数据
            page_skus = paginator.page(Page)
            total_count = paginator.count

            print(total_count)
            Set_Meal_Json_List = json.loads(serializers.serialize('json', page_skus))
            data_list = []
            for Set_Meal_Json in Set_Meal_Json_List:

                data_josn = Set_Meal_Json["fields"]
                CheckGroup_id = Set_Meal_Json['pk']  # 取检查项id
                data_josn["id"] = CheckGroup_id  # 将检查项id赋值给id字段
                # print(CheckGroup_id)
                data_list.append(data_josn)
            result = {
                "status": "200",
                "message": "获取检查套餐成功",
                "total_count": total_count,
                "data": data_list

            }
            print(data_list)
            return JsonResponse(result)

        else:
            setMeal_list = TSetmeal.objects.filter(Q(is_show=1) & Q(name__contains=queryString))
            paginator = Paginator(setMeal_list, pageSize)

            # 获取指定页码的数据
            page_skus = paginator.page(Page)
            total_count = paginator.count

            print(total_count)
            Set_Meal_Json_List = json.loads(serializers.serialize('json', page_skus))
            data_list = []
            for Set_Meal_Json in Set_Meal_Json_List:
                data_josn = Set_Meal_Json["fields"]
                CheckGroup_id = Set_Meal_Json['pk']  # 取检查项id
                data_josn["id"] = CheckGroup_id  # 将检查项id赋值给id字段
                # print(CheckGroup_id)
                data_list.append(data_josn)
            result = {
                "status": "200",
                "message": "获取检查套餐成功",
                "total_count": total_count,
                "data": data_list

            }
            print(data_list)
            return JsonResponse(result)
    def post(self, request):
        checkgroupIds = request.GET.get("checkgroupIds")
        request_json = request.body.decode("utf-8")
        data_dict = json.loads(request_json)
        res = TSetmeal.objects.create(
            code=data_dict["code"],
            name=data_dict["name"],
            helpcode=data_dict["helpCode"],
            sex=data_dict["sex"],
            remark=data_dict["remark"],
            attention=data_dict["attention"],
            price=data_dict["price"],
            age=data_dict["age"],
            img=data_dict["img"],
            is_show=1,
        )
        # 将检查项id添加到检查组中,中间表操作
        setmeal_id = res.setmeal_id
        checikGroupid_list = checkgroupIds.split(",")
        for checikGroupid in checikGroupid_list:
            TSetmealCheckgroup.objects.create(
                setmeal_id=setmeal_id,
                checkgroup_id=checikGroupid
            )
        # 使用reis进行缓存，方便清楚七牛云中多余的图片
        redisClient = redis.Redis()
        redisClient.sadd("ruici_img_bendi", data_dict['img'])
        redisClient.close()
        result = {
            "status": "200",
        }
        return JsonResponse(result)

    def delete(self, request):
        id = request.GET.get("id")
        print("------------------------------------------------------------------")
        print(id)
        checkGroup = TSetmeal.objects.get(setmeal_id=id)
        checkGroup.is_show = 0
        checkGroup.save()
        result = {
            "status": "200",
        }
        return JsonResponse(result)
    def put(self,request):

        checkgroupIds = request.GET.get("checkgroupIds")
        print(checkgroupIds)
        request_json = request.body.decode("utf-8")
        data_dict = json.loads(request_json)
        print(data_dict)
        Setmeal = TSetmeal.objects.get(setmeal_id=data_dict["id"])
        setmeal_id = Setmeal.setmeal_id
        print(setmeal_id)
        conn = pymysql.Connect(
            host="127.0.0.1",
            port=3306, user="root",
            password="123456",
            db="ruici",
            charset="utf8",
            autocommit=True
        )
        cursor = conn.cursor()
        sql=f"UPDATE t_setmeal set  code='{data_dict['code']}',name='{data_dict['name']}',helpcode='{data_dict['helpcode']}',remark='{data_dict['remark']}', attention = '{data_dict['attention']}' ,sex='{data_dict['sex']}',img='{data_dict['img']}',is_show='1' where id={setmeal_id}"
        cursor.execute(sql)

        sql2= f"delete from t_setmeal_checkgroup where setmeal_id  = '{setmeal_id}'"
        cursor.execute(sql2)

        checkgroupId_list = checkgroupIds.split(",")
        print(checkgroupId_list)
        for checkgroupId in checkgroupId_list:
            TSetmealCheckgroup.objects.create(
                checkgroup_id=checkgroupId,
                setmeal_id=setmeal_id
            )

        result = {
            "status": "200",
        }
        return JsonResponse(result)




#处理图片上传
class UploadImg(View):
        def post(self, request):
            form = UploadFileForm(request.POST,request.FILES)
            filename = form.files['imgFile']
            oldfilename = filename.name # 获取上传文件的原始名称
            newfilename= oldfilename.split('.')[0] + str(random.randint(10, 9999)) + '.' + oldfilename.split('.')[1]
            filePath = 'd://' + oldfilename #本地备份
            handle_uploaded_file(request.FILES['imgFile'],newfilename, filePath)
            #使用reis进行缓存，方便清楚七牛云中多余的图片
            redisClient =redis.Redis()
            redisClient.sadd("ruici_img","http://srajip2mc.hn-bkt.clouddn.com/"+newfilename)
            redisClient.close()

            data_json={
                "status": "200",
                "data":{
                    "imageName": newfilename
                }
            }
            print(data_json)
            return JsonResponse(data_json)
#编辑操作处理中间表
class TsetmealGroup(View):
    def get(self,request):
        setmealId = request.GET.get("setmealId")
        print(setmealId)
        conn = pymysql.Connect(
            host="127.0.0.1",
            port=3306, user="root",
            password="123456",
            db="ruici",
            charset="utf8",
            autocommit=True
        )
        cursor = conn.cursor()
        sql = f"select checkgroup_id from  t_setmeal_checkgroup where setmeal_id = '{setmealId}'"
        cursor.execute(sql)
        data_tuple = cursor.fetchall()
        print(data_tuple)
        data_list = []
        for data in data_tuple:
            data_list.append(data[0])
        print(data_list)
        result = {
            "status": "200",
            "data": data_list
        }
        return JsonResponse(result)
class clearImg(View):
    def get(self,request):
        #获取redis的差集
        redisClient = redis.Redis()
        data_res=img_list = redisClient.sdiff("ruici_img","ruici_img_bendi")
        for data_img_name in data_res:
            data_img_name = data_img_name.decode("utf-8 ")
            # 使用Redis客户端的srem方法从名为"ruici_img"的集合中移除指定的元素
            # 这里的data_img_name是要被移除的元素，通常代表某个图片的名称或标识
            redisClient.srem("ruici_img", data_img_name)
            # 从数据集中获取图片名称，通过去除URL前缀来提取图片的原始名称
            img_name = data_img_name[len("http://srajip2mc.hn-bkt.clouddn.com/"):]
            print(img_name)
            handle_delet_file(img_name)
            print("删除了垃圾图片------------->", img_name)
        result = {
            "status": "200",

        }
        return JsonResponse(result)
"""

  def get(self,request):
        # 获取Redis的差集
        redisClient = redis.Redis()
        data_img_names = redisClient.sdiff("ruici_img_upload","ruici_img_db")
        print(type(data_img_names))
        
        for data_img_name in data_img_names:
            clear_img_name = data_img_name.decode("utf-8")
            # 清除Redis
            redisClient.srem("ruici_img_upload",clear_img_name)
            img_name = clear_img_name[len("http://sp3as551j.hd-bkt.clouddn.com/"):]
            handle_clear_file(img_name)
            print("删除了垃圾图片------------->",img_name)

        return HttpResponse("ok!!!")



"""